package callnumber.gtdev5.com.photoVault.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

import com.alipay.sdk.app.PayTask;
import com.githang.statusbar.StatusBarCompat;
import com.gtdev5.geetolsdk.mylibrary.beans.PayResult;
import com.gtdev5.geetolsdk.mylibrary.callback.BaseCallback;
import com.gtdev5.geetolsdk.mylibrary.http.HttpUtils;
import com.gtdev5.geetolsdk.mylibrary.util.ToastUtils;

import org.litepal.crud.DataSupport;

import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import callnumber.gtdev5.com.photoVault.R;
import callnumber.gtdev5.com.photoVault.activity.FirstMainActivity;
import callnumber.gtdev5.com.photoVault.bean.ApliyBean;
import callnumber.gtdev5.com.photoVault.bean.UpdateBean;
import callnumber.gtdev5.com.photoVault.bean.Vip;
import callnumber.gtdev5.com.photoVault.utils.ActivityCollector;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by cheng
 * PackageName FakeCall_4
 * 2018/8/15 15:20
 */

public abstract class BaseActivity extends AppCompatActivity {
    public static Vip vip;
    protected Context mContext;
    protected Activity mActivity;
    private static final int SDK_PAY_FLAG = 1;
    protected PaysuccessListener PayListener;
    public static boolean isActive; //全局变量

    protected abstract int getLayouId();

    protected abstract void initViews(Bundle savedInstanceState);

    protected abstract void initDatas();

    protected abstract void initAction();

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    switch (payResult.getResultStatus()) {
                        case "9000":
                            updataVip();
                            if (PayListener != null) {
                                PayListener.PaySuccess();
                            }
                            break;
                        case "8000":
                            ToastUtils.showShortToast("正在处理中");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "4000":
                            ToastUtils.showShortToast("订单支付失败");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "5000":
                            ToastUtils.showShortToast("重复请求");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6001":
                            ToastUtils.showShortToast("已取消支付");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6002":
                            ToastUtils.showShortToast("网络连接出错");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        case "6004":
                            ToastUtils.showShortToast("正在处理中");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                        default:
                            ToastUtils.showShortToast("支付失败");
                            if (PayListener != null) {
                                PayListener.PayFail(payResult.getResultStatus());
                            }
                            break;
                    }


                    break;
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayouId());
        ButterKnife.bind(this);
        mActivity = this;
        StatusBarCompat.setStatusBarColor(this,
                getResources().getColor(R.color.white),
                true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = this.getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(R.color.white));
        }
        initViews(savedInstanceState);
        //获取vip状态
        runOnUiThread(() -> {
            if (DataSupport.findFirst(Vip.class) != null) {
                vip = DataSupport.findFirst(Vip.class);
            }
        });
        ActivityCollector.addActivity(this);
        initDatas();
        initAction();
    }

    @Override
    protected void onResume() {
        if (!isActive) {
            //app 从后台唤醒，进入前台
            isActive = true;
            Log.i("ACTIVITY", "程序从后台唤醒");
            Intent intent = new Intent(BaseActivity.this, FirstMainActivity.class);
            startActivity(intent);
        }
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (!isAppOnForeground()) {
            //app 进入后台
            isActive = false;//记录当前已经进入后台
            Log.i("ACTIVITY", "程序进入后台");
            ActivityCollector.finishAll();

        }
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
    }

    /**
     * APP是否处于前台唤醒状态
     *
     * @return
     */
    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)
            return false;

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }

        return false;
    }

    public void openActivity(Class<?> pClass) {
        openActivity(pClass, null);
    }

    public void openActivity(Class<?> pClass, Bundle mBundle) {
        Intent intent = new Intent(this, pClass);
        if (mBundle != null) {
            intent.putExtras(mBundle);
        }
        startActivity(intent);
    }

    public void openActionView(String url) {
        if (!TextUtils.isEmpty(url)) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_VIEW);
            intent.setData(Uri.parse(url));
            startActivity(intent);
        }

    }

    public interface PaysuccessListener {
        public void PaySuccess();

        public void PayFail(String resultstatu);
    }

    /**
     * 支付宝购买
     *
     * @param pid
     */
    protected void pay(int pid) {
        HttpUtils.getInstance().postOrder(1, pid, 0, 2, new BaseCallback<ApliyBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {
                ToastUtils.showShortToast("链接超时");
            }

            @Override
            public void onSuccess(Response response, ApliyBean apliyBean) {
                if (response.isSuccessful()) {
                    if (apliyBean != null) {
                        if (!apliyBean.isIssucc()) {
                            ToastUtils.showShortToast(apliyBean.getMsg());
                            return;
                        }
                        Runnable runnable = () -> {
                            PayTask alipay = new PayTask(mActivity);
                            Map<String, String> map = alipay.payV2(apliyBean.getPackage_str(), true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = map;
                            mHandler.sendMessage(msg);
                        };

                        Thread payThread = new Thread(runnable);
                        payThread.start();
                    }
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }

    protected void updataVip() {
        HttpUtils.getInstance().postUpdate(new BaseCallback<UpdateBean>() {
            @Override
            public void onRequestBefore() {

            }

            @Override
            public void onFailure(Request request, Exception e) {

            }

            @Override
            public void onSuccess(Response response, UpdateBean o) {
                if (o != null && response.isSuccessful()) {
                    vip = o.getVip();
                    if (DataSupport.findFirst(Vip.class) != null) {
                        DataSupport.deleteAll(Vip.class);
                    }
                    vip.save();
                }
            }

            @Override
            public void onError(Response response, int errorCode, Exception e) {

            }
        });
    }
}
